package net.daum.demo.Homework10;
 
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

import com.google.gson.Gson;

public class HelloAndroidActivity extends Activity {

    private static String TAG = "Homework10";

    /**
     * Called when the activity is first created.
     * @param savedInstanceState If the activity is being re-initialized after
     * previously being shut down then this Bundle contains the data it most
     * recently supplied in onSaveInstanceState(Bundle). <b>Note: Otherwise it is null.</b>
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "onCreate");
        setContentView(R.layout.main);
        
        AsyncTask<Void, Integer, HttpResponse> task = new AsyncTask<Void, Integer, HttpResponse>() {
			@Override
			protected HttpResponse doInBackground(Void... params) {
				try {
					String url = "http://auto.daum.net/json/makeList.daum";
					DefaultHttpClient client = new DefaultHttpClient();
					HttpGet request = new HttpGet(url);
					return client.execute(request);
				} catch (Exception e) {
					Log.e("TEST", "error", e);
				}

				return null;
			}

			@Override
			protected void onPostExecute(HttpResponse response) {
				if (response == null) {
					return;
				}
				
				try {
					String json = IOUtils.toString(response.getEntity().getContent());
					Make[] make = new Gson().fromJson(json, Make[].class);
					List<Make> list = new ArrayList<Make>();
					for (int i = 1; i < make.length; i++) {
						list.add(make[i]);
					}
					
					ListView listView = (ListView) findViewById(R.id.listView1);
					SampleAdapter sampleAdapter = new SampleAdapter(HelloAndroidActivity.this, list);
					listView.setAdapter(sampleAdapter);
				} catch (Exception e) {
					Log.e("TEST", "error", e);
				}
			}
		};
		task.execute();
    }
}

